package com.linkdood.app.config;


import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import lombok.extern.log4j.Log4j2;
import org.springframework.format.datetime.standard.InstantFormatter;

import java.io.IOException;
import java.text.ParseException;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Locale;

/**
 * LocalDateTime 反序列化 ISO-8601
 *
 * @author hycao
 */
@Log4j2
public class LocalDateTimeDeserializer extends StdDeserializer<LocalDateTime> {


    protected LocalDateTimeDeserializer(Class<?> vc) {
        super(vc);
    }

    public LocalDateTimeDeserializer() {
        this(LocalDateTime.class);
    }

    @Override
    public LocalDateTime deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
        String string = p.getValueAsString();
        if (string != null) {
            try {
                InstantFormatter instantFormatter = new InstantFormatter();
                Instant instant = instantFormatter.parse(string, Locale.US);
                return LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
            } catch (ParseException e) {
                log.warn("LocalDateTime parse failed, cause by:", e);
            }
        }
        return null;
    }
}
